<?php declare(strict_types=1);

/**
 * @package Sudoku (Light Portal)
 * @link https://custom.simplemachines.org/index.php?mod=4244
 * @author Bugo <bugo@dragomano.ru>
 * @copyright 2025 Bugo
 * @license https://opensource.org/licenses/MIT MIT
 *
 * @category plugin
 * @version 17.10.25
 */

namespace LightPortal\Plugins\Sudoku;

use Bugo\Compat\Theme;
use LightPortal\Plugins\Event;
use LightPortal\Plugins\GameBlock;
use LightPortal\Plugins\PluginAttribute;
use LightPortal\UI\Fields\RangeField;
use LightPortal\Utils\Str;

if (! defined('LP_NAME'))
	die('No direct access...');

/**
 * Generated by PluginMaker
 */
#[PluginAttribute(icon: 'fas fa-dice-d6')]
class Sudoku extends GameBlock
{
	private int $difficulty = 40;

	public function prepareBlockParams(Event $e): void
	{
		$e->args->params = [
			'difficulty' => $this->difficulty,
		];
	}

	public function validateBlockParams(Event $e): void
	{
		$e->args->params = [
			'difficulty' => FILTER_VALIDATE_INT,
		];
	}

	public function prepareBlockFields(Event $e): void
	{
		RangeField::make('difficulty', $this->txt['difficulty'])
			->setAttribute('min', 10)
			->setAttribute('max', 70)
			->setAfter('(%)')
			->setValue($e->args->options['difficulty']);
	}

	public function prepareContent(Event $e): void
	{
		[$id, $parameters] = [$e->args->id, $e->args->parameters];

		$langs = json_encode([
			'checkButton' => $this->txt['check_button'],
			'youWon'      => $this->txt['you_won'],
			'errors'      => $this->txt['errors'],
			'newGame'     => $this->txt['new_game'],
		]);

		$difficulty = Str::typed('int', $parameters['difficulty'], default: $this->difficulty);

		echo Str::html('div', [
			'id'    => 'sudoku' . $id,
			'class' => 'sudoku-game',
		])->toHtml();

		Theme::addInlineJavaScript('
			const sudoku' . $id . ' = document.getElementById("sudoku' . $id . '");
			new SudokuGame(sudoku' . $id . ', ' . $langs . ', ' . $difficulty . ');
		', true);
	}
}
